<!-- #layout name=blank -->
<div id="app">
  <div class="page-header">
    <h1 class="title">Styles</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <div class="btn-group navbar-btn">
        <button data-toggle="dropdown" class="btn green"
          ><span>Create</span> <i class="fa fa-angle-down"></i
        ></button>
        <ul role="menu" class="dropdown-menu">
          <li
            ><a :href="Kooboo.Route.Get(Kooboo.Route.Style.Create)"
              >Style</a
            ></li
          >
          <li><a @click="createGroup" href="javascript:;">Group</a></li>
        </ul>
      </div>
      <a class="btn green btn-file navbar-btn upload-link">
        <span>Upload styles</span>
        <input
          type="file"
          multiple
          v-kb-upload="{
                  allowMultiple: true,
                  acceptTypes: ['application/x-pointplus','text/css'],
                  acceptSuffix: ['css'],
                  callback: uploadStyle
              }"
        />
      </a>
      <a
        v-show="selectedRows.length>0"
        @click="onDelete"
        class="btn red navbar-btn"
        >Delete</a
      >
    </div>
  </div>
  <ul class="nav nav-tabs">
    <li
      v-for="item in tabs"
      :key="item.value"
      :class="{active:item.value==currentTab}"
    >
      <a href="javascript:;" @click="onTabClick(item.value)"
        >{{ item.displayName }}</a
      >
    </li>
  </ul>
  <kb-table
    :data="externalModel"
    v-if="currentTab=='External'"
    show-select
    :selected.sync="selectedRows"
    key="1"
    ref="table"
  >
    <kb-table-column :label="Kooboo.text.common.name">
      <template v-slot="row">
        <a :href="getDetailUrl(row.id)" @click.stop="">{{ row.name }}</a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.preview">
      <template v-slot="row">
        <a :href="row.fullUrl" target="_blank" @click.stop="">{{ row.name }}</a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.usedBy">
      <template v-slot="row">
        <a
          class="label label-sm kb-table-label-refer"
          :style="{
                          background: Kooboo.getLabelColor(item.key.toLowerCase())
                        }"
          v-for="(item, index) in Kooboo.objToArr(row.references)"
          :key="index"
          @click.stop="onShowRelationModal(item.key, row.id, Kooboo.Style.name)"
        >
          {{ item.value + " " +
          Kooboo.text.component.table[item.key.toLowerCase()] }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column width="10px">
      <template v-slot="row">
        <a
          class="btn blue btn-xs"
          :href="getVersionsUrl(row.keyHash,row.storeNameHash)"
          @click.stop=""
          target="_blank"
        >
          <i class="fa fa-clock-o"></i>
        </a>
      </template>
    </kb-table-column>
  </kb-table>
  <kb-table
    :data="embeddedModel"
    v-if="currentTab=='Embedded'"
    show-select
    :selected.sync="selectedRows"
    key="2"
  >
    <kb-table-column :label="Kooboo.text.common.name">
      <template v-slot="row">
        <a :href="getDetailUrl(row.id)" @click.stop="">{{ row.name }}</a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.usedBy">
      <template v-slot="row">
        <a
          class="label label-sm kb-table-label-refer"
          :style="{
                          background: Kooboo.getLabelColor(item.key.toLowerCase())
                        }"
          v-for="(item, index) in Kooboo.objToArr(row.references)"
          :key="index"
          @click.stop="onShowRelationModal(item.key, row.id, Kooboo.Style.name)"
        >
          {{ item.value + " " +
          Kooboo.text.component.table[item.key.toLowerCase()] }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>
  </kb-table>
  <kb-table
    :data="inlineModel"
    v-if="currentTab=='Inline'"
    show-select
    :selected.sync="selectedRows"
    key="3"
  >
    <kb-table-column :label="Kooboo.text.site.style.name" body-class="limit-col">
      <template v-slot="row">
        <a href="javascript:;" @click.stop="onShowInlineModal(row.id)"
          >{{ row.name }}</a
        >
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.style.ownerType">
      <template v-slot="row">
        <span
          class="label label-sm kb-table-label-refer"
          :style="{background: Kooboo.getLabelColor(row.ownerType)}"
          >{{ Kooboo.text.component.table[row.ownerType.toLowerCase()] }}</span
        >
      </template>
    </kb-table-column>

    <kb-table-column
      :label="Kooboo.text.site.style.siteObject"
      prop="ownerName"
    >
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>
  </kb-table>
  <kb-table
    :data="groupsModel"
    v-if="currentTab=='Group'"
    show-select
    :selected.sync="selectedRows"
    key="4"
  >
    <kb-table-column :label="Kooboo.text.common.name" body-class="limit-col">
      <template v-slot="row">
        <a href="javascript:;" @click.stop="editGroup(row.id)"
          >{{ row.name }}</a
        >
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.script.children">
      <template v-slot="row">
        <a
          class="badge blue"
          v-if="row.childrenCount"
          @click.stop="editGroup(row.id)"
        >
          {{ row.childrenCount }}
        </a>
        <span v-else>-</span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.usedBy">
      <template v-slot="row">
        <a
          class="label label-sm kb-table-label-refer"
          :style="{
                          background: Kooboo.getLabelColor(item.key.toLowerCase())
                        }"
          v-for="(item, index) in Kooboo.objToArr(row.references)"
          :key="index"
          @click.stop="onShowRelationModal(item.key, row.id, Kooboo.ResourceGroup.name)"
        >
          {{ item.value + " " +
          Kooboo.text.component.table[item.key.toLowerCase()] }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column width="200px" align="right">
      <template v-slot="row">
        <a class="btn blue" :href="row.previewUrl" target="_blank"
          >{{ Kooboo.text.common.preview }}</a
        >
      </template>
    </kb-table-column>
  </kb-table>
  <kb-relation-modal></kb-relation-modal>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showGroupModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">{{ groupModalTitle }}</h4>
        </div>
        <div class="modal-body" v-if="showGroupModal">
          <kb-form :model="groupModel" :rules="groupModelRules" ref="groupForm">
            <kb-form-item
              class="margin-bottom-20"
              prop="name"
              v-show="isGroupNew"
            >
              <label class="control-label col-md-2">Name</label>
              <div class="col-md-10">
                <input
                  type="text"
                  class="form-control"
                  v-model="groupModel.name"
                />
              </div>
            </kb-form-item>
            <div class="navbar navbar-default">
              <div class="container-fluid">
                <div class="navbar-form navbar-left">
                  <select
                    class="form-control"
                    v-model="selectedOption"
                    :style="{width:'200px'}"
                  >
                    <option
                      v-for="(item,index) in availableOptions"
                      :key="index"
                      :value="item.routeId"
                      >{{ item.name }}</option
                    >
                  </select>
                  <button
                    class="btn blue"
                    :disabled="!availableOptions.length"
                    @click="addGroupItem"
                    >Add</button
                  >
                </div>
              </div>
            </div>
            <table class="table table-striped table-hover">
              <thead>
                <tr>
                  <th class="table-sortable"></th>
                  <th>Style</th>
                  <th class="table-action"></th>
                </tr>
              </thead>
              <tbody
                v-if="groupModel.children.length"
                class="ui-sortable"
                v-kb-sortable="groupModel.children"
              >
                <tr v-for="(item,index) in groupModel.children" :key="index">
                  <td class="table-sortable"
                    ><span class="sortable ui-sortable-handle"
                      ><i class="glyphicon glyphicon-list"></i></span
                  ></td>
                  <td>{{ item.name }}</td>
                  <td>
                    <button
                      class="btn btn-xs red"
                      @click="removeGroupItem(item)"
                      >Remove</button
                    >
                  </td>
                </tr>
              </tbody>
              <tbody v-else>
                <tr>
                  <td colspan="100" class="text-center">Empty</td>
                </tr>
              </tbody>
            </table>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button class="btn green" @click="onGroupModalSubmit"
            >{{ Kooboo.text.common[isGroupNew ? "create" : "save"] }}</button
          >
          <button class="btn gray" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showInlineModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">Inline</h4>
        </div>
        <div class="modal-body" v-if="showInlineModal">
          <div class="block-style-editor" style="overflow: inherit;">
            <div id="inline_ed">
              <kb-style-list
                class="block-style-editor-v2 "
                ref="styleList"
                :rules="styleRules"
              ></kb-style-list>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="saveInlineModal" class="btn green">Save</button>
          <button data-dismiss="modal" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>
  <kb-media-dialog :data="mediaDialogData"></kb-media-dialog>
</div>
<style>
.limit-col {
  max-width: 400px;
}
</style>
<script>
  Kooboo.styleEditor = {};
</script>
<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/components/kbBreadcrumb.js",
      "/_Admin/Scripts/components/kbForm.js",
      "/_Admin/Scripts/components/kbTable.js",
      "/_Admin/Scripts/components/kbRelationModal.js",
      "/_Admin/Scripts/kooboo/Guid.js",
      "/_Admin/Scripts/lib/jquery-ui-customized.js",
      "/_Admin/Scripts/styleEditor/components/kb-style-list.js",
      "/_Admin/Scripts/components/kb-media-dialog.js",
      "/_Admin/Scripts/styleEditor/CSSRule.js",
      "/_Admin/Scripts/components/kbTypeahead.js",
      "/_Admin/Scripts/kooboo/Color.js",
      "/_Admin/Scripts/lib/bootstrap3-typeahead.min.js",
      "/_Admin/Scripts/lib/spectrum/spectrum-custom.js",
      "/_Admin/Scripts/components/kbUploadProgressor.js"
    ]);
    Kooboo.loadCSS(["/_Admin/Scripts/lib/spectrum/spectrum.css"]);
  })();
  new Vue({
    el: "#app",
    data: function() {
      return {
        breads: [
          {
            name: "SITES"
          },
          {
            name: "DASHBOARD"
          },
          {
            name: Kooboo.text.common.Styles
          }
        ],
        tabs: [
          {
            displayName: Kooboo.text.site.script.external,
            value: "External"
          },
          {
            displayName: Kooboo.text.site.script.embedded,
            value: "Embedded"
          },
          {
            displayName: Kooboo.text.site.style.inline,
            value: "Inline"
          },
          {
            displayName: Kooboo.text.site.script.group,
            value: "Group"
          }
        ],
        currentTab: "External",
        externalModel: [],
        embeddedModel: [],
        groupsModel: [],
        inlineModel: [],
        selectedRows: [],
        isGroupNew: false,
        showGroupModal: false,
        showInlineModal: false,
        groupModel: {
          id: "",
          name: "",
          typeName: Kooboo.Style.name,
          children: []
        },
        selectedOption: "",
        styleRules: [],
        mediaDialogData: null
      };
    },
    mounted: function() {
      var self = this;
      this.onTabClick("External");

      Kooboo.EventBus.subscribe("ko/style/list/pickimage/show", function(ctx) {
        Kooboo.Media.getList().then(function(res) {
          if (res.success) {
            res.model["show"] = true;
            res.model["context"] = ctx;
            res.model["onAdd"] = function(selected) {
              var _oldValue = ctx.value,
                regex = _oldValue.match(/url\((\S+)\)/);

              if (regex && regex.length) {
                var newValue = _oldValue
                  .split(regex[1])
                  .join("'" + selected.url + "'");
                ctx.value = newValue;
              } else {
                ctx.value = _oldValue + " url('" + selected.url + "')";
              }
            };
            self.mediaDialogData = res.model;
          }
        });
      });
    },
    methods: {
      saveInlineModal: function() {
        var self = this;
        setTimeout(function() {
          var rule = self.$refs.styleList.styleRules[0];
          var ruleText = "";
          _.forEach(rule.declarations, function(dec) {
            ruleText +=
              dec.name +
              ": " +
              dec.value +
              (dec.important ? " !important;" : ";");
          });

          Kooboo.CSSRule.updateInline({
            id: rule.id,
            ruleText: ruleText
          }).then(function(res) {
            if (res.success) {
              self.onTabClick("Inline");
              self.showInlineModal = false;
            }
          });
        }, 1000);
        $(".page-loading").show();
      },
      getVersionsUrl: function(keyHash, storeNameHash) {
        return Kooboo.Route.Get(Kooboo.Route.SiteLog.LogVersions, {
          KeyHash: keyHash,
          storeNameHash: storeNameHash
        });
      },
      getDetailUrl: function(id) {
        return Kooboo.Route.Get(Kooboo.Route.Style.DetailPage, {
          Id: id
        });
      },
      onShowRelationModal: function(by, id, type) {
        Kooboo.EventBus.publish("kb/relation/modal/show", {
          by: by,
          type: type,
          id: id
        });
      },
      createGroup: function() {
        this.isGroupNew = true;
        this.showGroupModal = true;
        this.groupModel.name = "";
        this.groupModel.id = Kooboo.Guid.Empty;
        this.groupModel.children = [];
        if (this.availableOptions.length) {
          this.selectedOption = this.availableOptions[0].routeId;
        }
      },
      editGroup: function(id) {
        var me = this;
        Kooboo.ResourceGroup.Get({ id: id }).then(function(res) {
          if (res.success) {
            me.isGroupNew = false;
            me.groupModel.id = id;
            me.groupModel.name = res.model.name;
            me.groupModel.children = res.model.children;
            me.showGroupModal = true;
            me.$nextTick(function() {
              if (this.availableOptions.length) {
                this.selectedOption = this.availableOptions[0].routeId;
              }
            });
          }
        });
      },
      addGroupItem: function() {
        var me = this;
        var selected = this.availableOptions.find(function(f) {
          return f.routeId == me.selectedOption;
        });
        if (selected) {
          this.$nextTick(function() {
            if (this.availableOptions.length) {
              me.selectedOption = me.availableOptions[0].routeId;
            }
          });
          this.groupModel.children.push(selected);
        }
      },
      removeGroupItem: function(item) {
        this.groupModel.children = this.groupModel.children.filter(function(f) {
          return f != item;
        });
      },
      onTabClick: function(tab) {
        var me = this;
        if (tab == "External") {
          Kooboo.Style.getExternalList().then(function(res) {
            if (res.success) {
              me.externalModel = res.model;
              me.selectedRows = [];
              me.currentTab = tab;
            }
          });
        } else if (tab == "Embedded") {
          Kooboo.Style.getEmbeddedList().then(function(res) {
            if (res.success) {
              me.embeddedModel = res.model;
              me.selectedRows = [];
              me.currentTab = tab;
            }
          });
        } else if (tab == "Inline") {
          Kooboo.CSSRule.getInlineList().then(function(res) {
            if (res.success) {
              me.inlineModel = res.model;
              me.selectedRows = [];
              me.currentTab = tab;
            }
          });
        } else {
          Kooboo.ResourceGroup.Style().then(function(res) {
            if (res.success) {
              me.groupsModel = res.model;
              me.selectedRows = [];
              me.currentTab = tab;
            }
          });
        }
      },
      uploadStyle: function(data, files) {
        var me = this;
        function upload() {
          var filesCount = files.length;
          var finishedCount = 0;
          files.forEach(function(file, idx) {
            var formdata = new FormData();
            formdata.append("file_" + idx, file);
            if (me.$refs.table && me.currentTab == "External") {
              file.progressor = {
                name: file.name,
                uploadPercentage: 0
              };
              file.setProgressor = function(rate) {
                file.progressor.uploadPercentage = rate;
              };
              me.$refs.table.progressorRows.push(file.progressor);
            }
            Kooboo.Upload.Style(formdata, file.setProgressor).then(function(
              res
            ) {
              if (res.success) {
                ++finishedCount;
                if (filesCount == finishedCount) {
                  if (me.$refs.table) me.$refs.table.progressorRows = [];
                  me.onTabClick("External");
                  window.info.show(Kooboo.text.info.upload.success, true);
                }
              }
            });
          });
        }

        if (files.length) {
          if (!Kooboo.isFileNameExist(files, this.externalModel)) {
            upload();
          } else {
            if (confirm(Kooboo.text.confirm.overrideFile)) {
              upload();
            }
          }
        }
      },
      onDelete: function() {
        var me = this;
        var haveRelations = this.selectedRows.some(function(s) {
          return s.relations && Object.keys(s.relations).length;
        });

        var confirmStr = haveRelations
          ? Kooboo.text.confirm.deleteItemsWithRef
          : Kooboo.text.confirm.deleteItems;

        var ids = this.selectedRows.map(function(m) {
          return m.id;
        });

        if (!confirm(confirmStr)) return;

        var name = "";
        switch (this.currentTab) {
          case "External":
          case "Embedded":
            name = Kooboo.Style.name;
            break;
          case "Inline":
            name = Kooboo.CSSRule.name;
            break;
          case "Group":
            name = Kooboo.ResourceGroup.name;
            break;
          default:
            break;
        }

        Kooboo[name]
          .Deletes({
            ids: ids
          })
          .then(function(res) {
            if (res.success) {
              me.onTabClick(me.currentTab);
              window.info.done(Kooboo.text.info.delete.success);
            } else {
              window.info.done(Kooboo.text.info.delete.fail);
            }
          });
      },
      onGroupModalSubmit: function() {
        if (this.$refs.groupForm.validate()) {
          var me = this;
          Kooboo.ResourceGroup.Update(JSON.stringify(this.groupModel)).then(
            function(res) {
              if (res.success) {
                me.showGroupModal = false;
                me.onTabClick("Group");
              }
            }
          );
        }
      },
      newID: function() {
        return Math.ceil(Math.random() * Math.pow(2, 53));
      },
      onShowInlineModal: function(id) {
        var self = this;
        Kooboo.CSSRule.getInline({
          id: id
        }).then(function(res) {
          if (res.success) {
            res.model.declarations.forEach(function(dec) {
              dec.id = self.newID();
            });
            self.styleRules = [res.model];
            self.showInlineModal = true;
          }
        });
      }
    },
    computed: {
      availableOptions: function() {
        var me = this;
        return me.externalModel.filter(function(f) {
          return !me.groupModel.children.some(function(s) {
            return s.routeId == f.routeId;
          });
        });
      },
      groupModalTitle: function() {
        return this.groupModel.name || Kooboo.text.site.script.groupName;
      },
      groupModelRules: function() {
        var me = this;
        var rules = {
          name: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^([A-Za-z][\w\-\.]*)*[A-Za-z0-9]$/,
              message: Kooboo.text.validation.objectNameRegex
            },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64
            }
          ]
        };
        if (this.isGroupNew) {
          rules.name.push({
            remote: {
              url: Kooboo.ResourceGroup.isUniqueName(),
              data: function() {
                return {
                  name: me.groupModel.name,
                  type: "style"
                };
              }
            },
            message: Kooboo.text.validation.taken
          });
        }
        return rules;
      }
    },
    watch: {}
  });
</script>
